#include "stdafx.h"
#include "ServiceImpDB.h"
#include "Message/DBMessage.h"


ServiceImpDB::ServiceImpDB()
:m_wpSvcLgc(NULL), m_initData(NULL)
{
}


void
ServiceImpDB::init(ServiceData& data)
{
	ServiceDataSMS* pSvcData = dynamic_cast<ServiceDataSMS*>(&data);
	if (pSvcData)
	{
		m_wpSvcLgc = pSvcData->m_wpSvcLgc;

		pSvcData->m_wpProperties->parse("db_server", m_initData.db_server);
		pSvcData->m_wpProperties->parse("db_name", m_initData.db_name);
		pSvcData->m_wpProperties->parse("db_user", m_initData.db_user);
		pSvcData->m_wpProperties->parse("db_password", m_initData.db_password);
		pSvcData->m_wpProperties->parse("db_port", m_initData.db_port);

		m_initData.wpSvcLgc = m_wpSvcLgc;
	}
}

void
ServiceImpDB::onStart()
{
	if (m_initData.db_name.empty() ||
		m_initData.db_server.empty() ||
		m_initData.db_user.empty() ||
		m_initData.db_password.empty() ||
		m_initData.db_port==0)
	{
		LOG_ERROR("Failed to connect to database, invalid db configurations: "<<m_initData.db_server<<", "<<m_initData.db_name<<", "<<m_initData.db_user<<", "<<m_initData.db_password<<", "<<m_initData.db_port);
		return;
	}
	else if (!m_PersistMsgHandler.initialize(&m_initData))
	{
		LOG_ERROR("Failed to connect to database, please check you database or configurations!");
	}

	__super::onStart();
}

void
ServiceImpDB::onStop()
{
	__super::onStop();
}


void
ServiceImpDB::onTimer()
{
	//LOG_DEBUG(" Timeout, Database Thread!!!");

	__super::onTimer();
}

void
ServiceImpDB::onDispatchMsg(IMsg* pMsg)
{
	if ( !m_PersistMsgHandler.handleMsg( pMsg ) )
	{
		pMsg->dump();
		LOG_ERROR("Failed to handle upper db message!");
	}

	m_wpSvcLgc->postMsg(pMsg);
}
